<template>
  <div
    class="main-header"
    :class="{ 'to-top' : isHideSideBar}"
    v-cloak
  >
    <a
      href="javascript:;"
      class="logo"
    >
      <div
        v-if="logoObj.logoImg"
        class="logo-box"
      ><img
          :src="logoObj.logoImg"
          alt=""
        ></div>
      <div
        v-else
        class="logo-box"
      ><img
          src="../assets/img/title.png"
          alt=""
        ></div>
    </a>
    <nav class="navbar">
      <a
        href="javascript:;"
        class="prev-item more-item"
        v-show="showPrevBtn"
        @click="clickPrevItem"
      >
        <span class="more-menu-icon"></span>
      </a>
      <div
        id="menu_box"
        class="menu-box"
      >
        <div
          class="menu-inner-box"
          :style="menuStyle"
        >
          <a
            class="menu-item"
            v-for="(item, index) in menuList.list"
            :data-id="item.id"
            :key="index"
            :class="index === menuList.active ? 'active' : ''"
            @click.prevent="clickOneMenu(index, item.childList)"
          >{{item.name}} 0000</a>
        </div>
      </div>
      <a
        href="javascript:;"
        class="next-item more-item"
        v-show="showNextBtn"
        @click="clickNextItem"
      >
        <span class="more-menu-icon"></span>
      </a>
    </nav>
    <ul class="btnbar list-inline">
      <li class="btn-item">
        <a @click="openDownloadModal('downloadModal')">
          <i class="down-icon"></i>
        </a>
      </li>
      <li class="btn-item dropdown">
        <a
          :class="{active: isShowUserInfo}"
          @click="isShowUserInfo = !isShowUserInfo"
        >
          <i class="btnbar-icon user-icon"></i>
        </a>
        <personal-info
          :is-show-user-info="isShowUserInfo"
          :user-info="userInfo"
        ></personal-info>
      </li>
      <li class="btn-item">
        <a @click.prevent="toOpenModal('logout')">
          <i class="btnbar-icon sign-out-icon"></i>
        </a>
      </li>
    </ul>
    <basic-modal
      ref="logout"
      title-txt="退出系统"
      body-txt="您确定要退出系统吗?"
      yes-txt="确定"
      cancel-txt="取消"
      v-on:confirm="confirmLogout"
    >
    </basic-modal>

    <!--导出记录-->
    <basic-modal
      ref="downloadModal"
      width="1050"
      customeClass="surpport-park-modal"
      static="true"
      @closing="whenDownLoadModal()"
    >
      <h3 slot="title">导出记录</h3>
      <div
        class="modal-body"
        slot="modal-body"
      >
        <template>
          <el-table
            border
            :data="orderExportList"
            style="width: 100%; height: 280px!important"
            :height="300"
          >
            <el-table-column
              :label="item.text"
              :minWidth="item.minWidth"
              v-for="(item,index) in downloadModalTable.theadsInfo"
              :key="index"
            >
              <template slot-scope="scope">
                <span v-if="'reno' == item.prop">{{ scope.$index + 1 }}</span>
                <span v-else-if="'createTime' == item.prop">{{scope.row.createTime|mileSecondToDate}}</span>
                <span v-else-if="'expiredTime' == item.prop">{{scope.row.expiredTime|mileSecondToDate}}</span>
                <span v-else-if="'progress' == item.prop">{{scope.row.progress|formatMoney}}%</span>
                <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              minWidth="120"
            >
              <template slot-scope="scope">
                <el-button
                  @click="delItem(scope.row)"
                  size="small"
                  type="primary"
                  class="ake_btn ake_font_btn ake_btn_red"
                  icon="el-icon-delete"
                  v-if="scope.row.status==3"
                  title="删除"
                ></el-button>
                <el-button
                  @click="downloadItem(scope.row)"
                  size="small"
                  type="primary"
                  class="ake_btn ake_font_btn ake_btn_red"
                  icon="el-icon-download"
                  v-if="scope.row.status==3"
                  title="下载"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="pagination-box">
          <el-pagination
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageNumber"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, prev, pager, next,sizes"
            :total="downloadModalTable.total"
          >
          </el-pagination>
        </div>
      </div>
      <div
        class="modal-footer"
        slot="modal-footer"
      >
        <button
          class="ake_btn ake_btn_text modal-close"
          @click="closedDownloadModal('downloadModal')"
        >关闭</button>
      </div>
    </basic-modal>

  </div>
</template>
<script>
let singleMenuW = 100;
import common from "../mixins/common.js";
import { mapState, mapGetters, mapMutations } from "vuex";
// import menuList from "../assets/js/menu.js";
import stardardList from "@mixins/tables/stardardList.js";
import PersonalInfo from "./head/PersonalInfo.vue";
import BasicModal from "./widgets/BasicModal";
import invokeModal from "../mixins/modal/invokeModal.js";
import api from "../fetch/api.js";
export default {
  mixins: [common, stardardList, invokeModal],
  data() {
    return {
      total: 0,
      currentPage: 1,
      downloadModalTable: {
        total: 0,
        theadsInfo: [
          {
            index: 0,
            isShow: false,
            prop: "reno",
            text: "序号",
            minWidth: 50
          },
          {
            index: 1,
            isShow: false,
            prop: "filename",
            text: "文件名",
            minWidth: 220
          },
          {
            index: 2,
            isShow: false,
            prop: "createTime",
            text: "创建时间",
            minWidth: 140
          },
          {
            index: 3,
            isShow: false,
            prop: "expiredTime",
            text: "过期时间",
            minWidth: 140
          },
          {
            index: 4,
            isShow: false,
            prop: "progress",
            text: "进度",
            minWidth: 68
          },
          {
            index: 5,
            isShow: false,
            prop: "statusStr",
            text: "状态",
            minWidth: 68
          }
        ]
      },
      orderExportList: [],
      orderExportUpdateList: [],
      showPrevBtn: false,
      showNextBtn: false,
      translateW: 0,
      menuStyle: {
        width: "auto",
        transform: "translate3d(0,0,0)"
      },
      isShowUserInfo: false,
      userInfo: {}
    };
  },
  components: {
    "personal-info": PersonalInfo,
    "basic-modal": BasicModal
  },
  computed: {
    ...mapGetters({
      isHideSideBar: "getIsHideSideBar",
      menuList: "getAllMenu"
    }),
    ...mapState({
      logoObj: "logoObj"
    }),
    ...mapState({
      carrierId: ""
    })
  },
  created() {
    let _this = this;
    let resizeTimer = null;

    // this.getAllMenuFn(menuList);

    this.getResources();

    $(window).on("resize", function() {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function() {
        _this.initNav();
      }, 50);
    });

    $(document).on("click", function(e) {
      let $Target = $(e.target);
      if ($Target.closest(".dropdown").length > 0) {
        return;
      }
      _this.isShowUserInfo = false;
    });
  },
  mounted() {
    this.initNav();
  },
  methods: {
    ...mapMutations({
      set_perms: "SET_PERMS"
    }),
    ...mapMutations(["setLogoObj"]),
    ...mapMutations(["setCarrierId"]),
    setMenus(menus) {
      let ismenu = JSON.parse(window.sessionStorage.getItem("allMenu"))
        ? true
        : false;
      if (!ismenu) {
        window.sessionStorage.setItem("allMenu", JSON.stringify(menus));
      }
    },
    whenDownLoadModal() {
      var self = this;
      self.orderExportUpdateList = [];
      console.log("whenDownLoadModal");
    },
    handleCurrentChange(val) {
      var self = this;
      self.pageNumber = Number(val);
      self.searchItem();
    },
    handlePageSizeChange(val) {
      var self = this;
      self.pageSize = Number(val);
      self.searchItem();
    },
    searchItem() {
      var self = this;
      var params = {
        page: self.pageNumber,
        rp: self.pageSize
      };
      API.FindOrderExportList(params).then(
        res => {
          var data = res;
          self.orderExportList = data.data.rows;
          self.orderExportUpdateList = data.data.rows;
          // self.downloadModalTable.total = 100;
          self.downloadModalTable.total = data.data.total;

          setTimeout(function() {
            self.updateItem(self);
          }, 2000);
        },
        err => {}
      );
    },
    updateItem(self) {
      function intervalFunc() {
        $.ajax({
          url: "/mgr/authz/user/findOrderExportList.do",
          dataType: "json",
          data: {
            page: self.pageNumber,
            rp: self.pageSize
          },
          type: "get",
          success: function(result) {
            if (result.status == 1) {
              var tmpList = result.data.rows;
              self.orderExportList = tmpList;
              //self.orderExportUpdateList = tmpList;
              self.downloadModalTable.total = result.data.total;
              // self.downloadModalTable.total = 100;

              //先判断是否有需要
              if (
                !self.orderExportUpdateList ||
                self.orderExportUpdateList.length == 0
              ) {
                clearInterval(getOrderExportUpdateListTimer);
              }

              self.orderExportUpdateList = [];
              for (var i = 0; i < tmpList.length; i++) {
                var t = tmpList[i];
                if (t.status == 0 || t.status == 1) {
                  self.orderExportUpdateList.push(t);
                }
              }
              console.log(self.orderExportUpdateList);
            }
          }
        }); //ajax end
      }
      intervalFunc();
      var getOrderExportUpdateListTimer = setInterval(function() {
        intervalFunc();
      }, 2000); //interval end
    },
    closedDownloadModal(modalName) {
      var self = this;
      // self.orderExportUpdateList = [];
      self.closed(modalName);
    },
    openDownloadModal(modalName) {
      var self = this;
      self.orderExportList = [];
      self.orderExportUpdateList = [];
      self.searchItem();
      self.toOpenModal(modalName);
    },
    delItem(row) {
      var self = this;
      self.showDialog(
        "文件[" + row.filename + "]是否确认删除?",
        "",
        function() {
          API.DelOrderExport({ id: row.id }).then(
            res => {
              self.searchItem();
            },
            err => {}
          );
        }
      );
    },
    downloadItem(row) {
      var self = this;
      self.showDialog(
        "文件[" + row.filename + "]是否确认下载?",
        "",
        function() {
          self.toExport("authz/user/downloadOrderExport.do", { id: row.id });
        }
      );
    },
    getResources() {
      let self = this;
      // console.log(self.loadMenuEnd);
      API.GetMenu()
        .then(
          res => {
            self.getAllMenuFn(res.menus);
            self.filterPerms(res.perms);
            self.userInfo = res.user;
            self.loadMenuEnd = true;
            //  console.log(self.loadMenuEnd);
            self.setMenus(res.menus);
            localStorage.setItem("session_key", res.session_key);
          },
          err => {
            self.jumpToLogin();
          }
        )
        .catch(error => {
          self.jumpToLogin(); // console.log(error)
        });
    },
    //把拥有权限的按钮过滤出来
    filterPerms(perms) {
      let permsArr = perms
        .filter(function(x) {
          return x.type == 2 && x.permission;
        })
        .map(x => {
          return x.permission;
        });
      this.set_perms(permsArr);
      sessionStorage.setItem("perms", JSON.stringify(permsArr));
    },
    getAllMenuFn(menuLists) {
      let _first = this.menuList.active || 0;
      // let _side =
      let allMenuList = menuLists && menuLists.length > 0 ? menuLists : [];
      let sideMenuList =
        allMenuList.length > 0 ? menuLists[_first].childList : [];
      let initSideMenu = { list: sideMenuList, firstIndex: _first };
      this.$store.commit("SET_ALLMENU", { list: allMenuList, active: _first });
      this.$store.commit("SET_SIDEMENULIST", initSideMenu);
      this.$nextTick(function() {
        this.initNav();
      });
    },
    initNav() {
      let nav_wrapper_w = $("#menu_box").width();
      let nav_w = this.menuList.list.length * singleMenuW;
      // console.log(nav_w)
      // console.log(nav_wrapper_w)
      if (nav_w > nav_wrapper_w) {
        this.showPrevBtn = false;
        this.showNextBtn = true;
        if (this.translateW < 0) {
          this.showPrevBtn = true;
        }
      } else {
        this.showPrevBtn = false;
        this.showNextBtn = false;
        if (this.translateW != 0) {
          this.translateW = 0;
          this.menuStyle.transform = "translate3d(0,0,0)";
        }
      }

      this.menuStyle.width = nav_w + "px";
    },
    clickOneMenu(index, children) {
      console.log(index, children);
      let sideMenu = {
        list: children || [],
        firstIndex: index
      };
      // this.activeMenu = index;
      this.$store.commit("SET_ALLMENU", { active: index });
      this.$store.commit("SET_SIDEMENULIST", sideMenu);
    },
    //菜单项往前移动一个
    clickPrevItem() {
      let translateW = this.translateW;
      let nav_len = this.menuList.list.length;
      let nav_wrapper_w = $("#menu_box").width();
      let nav_w = nav_len * singleMenuW;
      if (Math.abs(translateW) > 0) {
        if (translateW + singleMenuW >= 0) {
          translateW = 0;
          this.showPrevBtn = false;
          this.showNextBtn = true;
        } else {
          var reste = Math.abs(translateW) % singleMenuW; //如果当前视线范围内的第一个菜单不是完整显示的，则往后移动 宽度/单个菜单宽度的余数
          translateW += reste > 0 ? reste : singleMenuW;
          if (nav_wrapper_w + Math.abs(translateW) >= nav_w) {
            this.showNextBtn = false;
          } else {
            this.showNextBtn = true;
          }
        }
        this.translateW = translateW;
        this.menuStyle.transform =
          "translate3d(" + this.translateW + "px, 0, 0)";
      }
    },
    //菜单项往后移动一个
    clickNextItem() {
      let nav_len = this.menuList.list.length;
      let nav_wrapper_w = $("#menu_box").width();
      let nav_w = nav_len * singleMenuW;
      let this_translateW = 0;

      if (nav_w > nav_wrapper_w) {
        if (nav_wrapper_w + Math.abs(this.translateW) + singleMenuW >= nav_w) {
          this_translateW =
            nav_wrapper_w + Math.abs(this.translateW) + singleMenuW - nav_w;
          this_translateW = singleMenuW - this_translateW;
          this.showNextBtn = false;
          this.translateW -= this_translateW;
        } else {
          this_translateW = singleMenuW;
          this.translateW -= singleMenuW;
        }
        this.menuStyle.transform =
          "translate3d(" + this.translateW + "px, 0, 0)";
        this.showPrevBtn = true;
      }
    },

    confirmLogout() {
      let self = this;
      API.login.Logout({}).then(
        res => {
          self.$store.commit("SET_NEEPADDPARKINGLOTINGLOT", false);
          //设置运营商id

          if (res.data && !res.data.carrierId) {
            window.sessionStorage.setItem("_carrierId", null);
          } else {
            self.id = res.data.carrierId;
            self.setCarrierId(self.id);
            window.sessionStorage.setItem(
              "_carrierId",
              JSON.stringify(self.id)
            );
          }

          //logout操作
          self.closed("logout");
          self.jumpToLoginAfterLogout();
          let Obj = {
            logoImg: null,
            loginImg: null,
            homepageImg: null
          };
          window.sessionStorage.setItem("_LogoObj", Obj);
          self.setLogoObj(Obj);
        },
        err => {
          console.log(err);
          self.showToast(err.data.message, 2); //"退出失败,请重试!"
        }
      );
    }
  }
};
</script>

<style lang="less">
.surpport-park-modal .el-table {
  height: 280px !important;
}
// .modal-body {
//   height: 500px;
// }
</style>

<style lang="less" scoped>
@import "../assets/less/base/common.less";
@import "../assets/less/header.less";
.pagination-box {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}
// .surpport-park-modal {
//   padding-bottom: 30px;
//   .modal-body {
//     max-height: 480px;
//     min-height: 300px;
//     overflow-y: scroll;
//   }
//   #downloadModalTable {
//     max-height: 480px;
//     min-height: 300px;
//   }
// }
</style>
